//
//  ZLHomeViewController.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 16/12/15.
//  Copyright © 2016年 hanju001. All rights reserved.
//

import UIKit

//使用private修饰负责到处都可以访问了
private let originalcellID = "cellID"

private let reweetCellId = "retweetCellID"

class ZLHomeViewController: ZLBaseViewController {

    fileprivate lazy var listViewModel = ZLStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(browserPhoto), name: NSNotification.Name(rawValue: ZLStatusCellBrowserPhotoNotification), object: nil)
        
    }
    deinit {
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }

    //浏览照片通知监听方法
    @objc private func browserPhoto(noti: NSNotification){
        
        //从usrInfo提取参数
        guard let selectedIndex = noti.userInfo?[ZLSatatusCellBrowserPhotoSlectedIndexKey] as? Int, let urls = noti.userInfo?[ZLSatatusCellBrowserPhotoURLSKey] as? [String], let imageViewList = noti.userInfo?[ZLSatatusCellBrowserPhotoImageViewsKey] as? [UIImageView] else{
            
            return
        }
        //展现照片浏览的控制器
        let vc = HMPhotoBrowserController.photoBrowser(withSelectedIndex: selectedIndex, urls: urls, parentImageViews: imageViewList)
        
        present(vc, animated: true, completion: nil)
        
    }
    override func loadData() {
        
        
        refreshControl?.beginRefreshing()
        
        //模拟延时加载数据
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { 
            self.listViewModel.loadStatus(pullup: self.isPullup) { (isSucess, hasMorePullup) in
                
                
                //结束刷新控件
                self.refreshControl?.endRefreshing()
                
                //恢复上拉率先呢标记
                self.isPullup = false
                
                if hasMorePullup{
                    
                    self.tableView?.reloadData()
                }
                
            }
        }
        
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @objc fileprivate func showFrends() -> () {
        
        print(#function)
        let vc = ZLDemoViewController()
        
        navigationController?.pushViewController(vc, animated: true)
        
    }


}
// MARK -- 表格数据源方法
extension ZLHomeViewController{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewmodel = listViewModel.statusList[indexPath.row]
        
        let cellid = viewmodel.status.retweeted_status != nil ? reweetCellId : originalcellID
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellid, for: indexPath) as! ZLStatusCell
        
        
        cell.vieModel = viewmodel
        //设置代理
        cell.delegate = self;
        
        return cell;
    }
    //没有override2.0没关系 在swift3.0不会被调用 解决办法需要取消自动行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        //根据indexpath获取视图模型
        let vm = listViewModel.statusList[indexPath.row]
        
        return vm.rowHeight
        
    }
    
}
extension ZLHomeViewController
{
    override func setupTableView() {
        super.setupTableView()
        
        //设置导航栏按钮
        //swift调用OC返回的instance  无法判断类型
        /*let btn: UIButton = UIButton.hm_textButton("好友", fontSize: 16, normalColor: UIColor.darkGray, highlight: UIColor.orange)
         btn.addTarget(self, action: #selector(showFrends), for: .touchUpInside)
         
         
         navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)*/
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontsize: 16, target: self, action: #selector(showFrends))
        
        //注册cell
        
        tableView?.register( UINib(nibName: "ZLStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalcellID)
        tableView?.register( UINib(nibName: "ZLStatusReweetCell", bundle: nil), forCellReuseIdentifier: reweetCellId)
        
        ///tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 100;
       
        tableView?.separatorStyle = .none
        
        setNaviTitle()
        
    }
    fileprivate func setNaviTitle(){
        
        let title = ZLNetWorkManager.shared.userAcount.screen_name
        let button = ZLTitlebutton(title: title)
        navItem.titleView = button;
        
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    }
    @objc private func clickTitleButton(btn: UIButton){
    
        btn.isSelected = !btn.isSelected
        
    }
    
}
/// MARK -- ZLStatusCellDelegate
extension ZLHomeViewController: ZLStatusCellDelegate {
    
    func statusCellDidTapURLString(cell: ZLStatusCell, urlString: String) {
        
        let vc = ZLWebViewController()
        vc.urlString = urlString
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
}

